package com.example.leo.mycharmingstudent.a0914;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.example.leo.mycharmingstudent.R;
import com.example.leo.mycharmingstudent.a0905.ToastUtil;

import java.io.Serializable;

public class BActivity extends AppCompatActivity {

    //回传数据给A Activity  按钮
    private Button btnBackA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);

        findViews();
        initData();
        initEvent();

    }

    private void findViews() {
        btnBackA = findViewById(R.id.btn_back_a_activity_b);
    }

    private void initData() {
        Intent intent = getIntent();
        //如果确定传来的参数类型是StudentEntity，可以直接强转
//        StudentEntity student = (StudentEntity) intent.getSerializableExtra("student");
        //如果不确定传来的参数类型是StudentEntity，不可以直接强转
        Serializable student = intent.getSerializableExtra("student");
        /*
        判断某个对象，是不是某种类型，使用instanceof
        student（对象） instanceof StudentEntity（类）
         */
        if (student instanceof StudentEntity) {
            //因为已经判定student对象是StudentEntity类型，强转安全
            StudentEntity studentEntity = (StudentEntity) student;
            ToastUtil.showToast(this,String.format("name:%s age:%s sex:%s weight:%s height:%s",
                    studentEntity.getName(),
                    studentEntity.getAge(),
                    studentEntity.getSex(),
                    studentEntity.getWeight(),
                    studentEntity.getHeight()));
        }

        StudentEntityParcelable parcel = intent.getParcelableExtra("parcel");
        if (parcel != null) {
            ToastUtil.showToast(this,String.format("name:%s age:%s",
                    parcel.name,
                    parcel.sex));
        }
    }

    private void initEvent() {
        //小思考：这个地方可以使用this，但是，现在为什么报错？
//        btnBackA.setOnClickListener(this);
        btnBackA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回传数据（结果）给A Activity
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("data", "村长回来了~");
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }
}
